<template>
    <div class="UserAdd">
        <div>
            <a-button type="primary" @click="showModal"> 
                <Component is="UserAddOutlined"></Component> 添加用户
            </a-button>
            <a-modal v-model:open="open" width="40%" title="添加用户" @ok="onSubmit" >
                <a-form
                    ref="formRef"
                    :model="formState"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-item ref="name" label="Username" name="name" required>
                        <a-input v-model:value="formState.name" >
                            <template #prefix> 
                                <Component is="UserOutlined"></Component>
                            </template>
                        </a-input>
                    </a-form-item>
                    <a-form-item label="Password"  name="password"  required>
                        <a-input-password v-model:value="formState.password">
                            <template #prefix> 
                                <Component is="LockOutlined"></Component>
                            </template>
                        </a-input-password>
                    </a-form-item>
                    <a-form-item label="角色"  name="role_ids"  required>
                        <!-- 
                            @popupScroll="popupScroll" -->
                        <a-select
                            v-model:value="formState.role_ids" 
                            mode="multiple"
                            size="middle"
                            placeholder="Please select" 
                        >
                            <a-select-option 
                                v-for="item in options" 
                                :key="item.role_id" 
                                :value="item.role_id" 
                            >
                                {{ item.role_name }}
                            </a-select-option> 
                        </a-select>
                    </a-form-item>
                    <a-form-item  label="昵称" name="nickname">
                        <a-input v-model:value="formState.nickname" > </a-input>
                    </a-form-item>
                    <a-form-item  label="邮箱" name="email">
                        <a-input v-model:value="formState.email" > </a-input>
                    </a-form-item> 

                    <a-form-item label="是否禁用" name="delivery">
                        <a-switch v-model:checked="formState.delivery" />
                    </a-form-item> 
                </a-form>
            </a-modal>
        </div>
        <div>
            <a-input-search
                v-model:value="searchValue"
                placeholder="请输入用户名"
                enter-button
                @search="onSearch"
            />
        </div>
    </div>
    <a-table 
        :data-source="userSurface.userList" 
        :columns="columns" 
        bordered 
        :pagination="pagination" 
        :loading="isLoading"
        >
        <template #bodyCell="{ column, text }"> 
                <template v-if="column.dataIndex === 'user_pic'">
                    <div>   
                        <img :src="https+convertBackslashToSlash(text)" >
                    </div> 
                </template> 
                <template v-else-if="column.dataIndex === 'roles'">
                    <a-tag
                        v-for="tag in text"
                        :key="tag.role_id"
                        :color="tagColor(tag.role_id)"
                    >
                        {{ tag.role_name.toUpperCase() }}
                    </a-tag>
                </template> 
                <template v-else-if="column.dataIndex === 'status'">
                    <a-tag :color="text=='1'?'#87d068':'#f50'">{{ text=='1'?'启用':'禁用' }}</a-tag>
                </template> 
                <template v-else-if="column.dataIndex === 'operation'"> 
                    <div class="operation">
                        <a-button type="primary" size="small"> 
                            <Component is="EditFilled"></Component>编辑
                        </a-button>
                        <a-button type="primary" style="background-color:#F7B500 ;" size="small">
                            <Component is="RedoOutlined"></Component>重置密码
                        </a-button>
                        <a-button type="primary" danger size="small"> 
                            <Component is="DeleteFilled"></Component> 删除
                        </a-button>
                    </div>
                </template> 
        </template>
    </a-table> 
</template>

<script setup lang='ts'>
    import {ref,reactive,toRaw} from 'vue'
    import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
    import { userList ,roleList} from '@/api/index' 
    const https = 'http://47.115.218.105:9999/'
    
    
    

    const searchValue = ref<string>('');//搜索
    /**
     * 用户列表
     */
    const isLoading = ref(false)
    const columns = [
        {
            title: '头像', 
            dataIndex: 'user_pic', 
            align:'center',
        },
        {
            title: '用户名',
            dataIndex: 'username', 
            align:'center',
        },
        {
            title: '昵称',
            dataIndex: 'nickname', 
            align:'center',
        },
        {
            title: '邮箱', 
            dataIndex: 'email',
            align:'center',
        },
        {
            title: '角色',
            dataIndex: 'roles',
            align:'center',
        },
        {
            title: '用户状态',
            dataIndex: 'status',
            align:'center',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align:'center',
            minWidth:300,
            // maxwidth:300,
            // width:300,
        },
    ]; 
    const userSurface = reactive({
        userList:[], 
    })
    // 表格分页的配置
    const pagination = reactive({ 
        current: 1,
        pageSize: 2,
        showSizeChanger: true, // 用于控制展示每页多少条的下拉
        showQuickJumper:true,
        total: 0,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total) => `共 ${total} 条`,
        onShowSizeChange: pageSizeChange,
        onChange: pageChange,
    }); 
    // 点击某页
    function pageSizeChange(val, pageNum){
        pagination.pageSize = pageNum; // 修改每页显示的条数
        pagination.current = 1;
        getUserList()
    }
     // 点击上一页下一页的方法
    function pageChange(page, val){ 
        pagination.current = page;
        getUserList()
    }
    // 获取用户列表数据
    const getUserList = async()=>{ 
        isLoading.value = true
        let paging = {
            pageSize:pagination.pageSize,//每页数量
            currentPage:pagination.current,//当前页码
            username:null, //可用于搜索参数 
        }
        let res = await userList(paging) 
        if (res.code == 0) {
            userSurface.userList = res.data.rows 
            pagination.total = res.data.count
            isLoading.value = false
        }
    }
    getUserList()
    // img地址转换
    function convertBackslashToSlash(path:any) {
        if (path) {
            return path.replace(/\\/g, '/');
        }
        
    }
    // 返回角色tag颜色
    const tagColor = (color:number)=>{ 
        if (color == 1) {
            return 'success'// 管理员
        }else if(color==2){
            return 'processing'
        } 
    }

    /**
     * 
     * 添加用户
     */
    let role_list = reactive([])
    const open = ref<boolean>(false);//弹窗
    import type { UnwrapRef } from 'vue';
    import type { Rule } from 'ant-design-vue/es/form'; 
   
    interface FormState <T = any> {
        name: string;
        password:string;
        role_ids:Array<T>;
        nickname:string;
        email:string;
        region: string | undefined;
        date1:   undefined;
        delivery: boolean;
        type: string[];
        resource: string;
        desc: string;
    }
    const rules: Record<string, Rule[]> = {
        name: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
            { pattern:/^[a-zA-Z0-9_]{6,20}$/, message: '用户名只能包含字母、数字和下划线,长度在10到20位之间', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '用户名密码不能为空', trigger: 'blur' },
            { pattern:/^(?:[0-9]){6,10}$/, message: '密码必须由6到10位数字组成', trigger: 'blur' },
        ],
        role_ids: [{ required: true, message: '角色不能为空', trigger: 'change'}], 
        email:[{ pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址', trigger: 'blur' },]
    };
    let options = reactive([])

    const formRef = ref();
    const labelCol = { span: 5 };
    const wrapperCol = { span: 13 };
    const formState: UnwrapRef<FormState> = reactive({
        name: '',
        password:'',
        role_ids:[],
        nickname:'',
        email:'',
        region: undefined,
        date1: undefined,
        delivery: false,
        type: [],
        resource: '',
        desc: '',
    });
    const showModal = () => { //显示弹窗
        open.value = true;
    };
    const handleOk = (e: MouseEvent) => { //关闭弹窗
        console.log(e);
        open.value = false;
    };
    const onSubmit = () => {
    formRef.value
        .validate()
        .then(() => {
        console.log('values', formState, toRaw(formState));
        })
        .catch(error => {
        console.log('error', error);
        });
    };
    const obtainRole_list = async() =>{
        let pramas = {
            pageSize:0,
            currentPage:0,
        }
        let result = await roleList(pramas)
        console.log(result);
        if (result.code == 0) {
            options = result.data.rows
        }
        
    }
    obtainRole_list()
    /**
     * 
     * 搜索
     */
    const onSearch = (searchValue: string) => {
        console.log(searchValue); 
    };

</script>

<style lang='less' scoped>
    .operation{
        // display: flex;
        // justify-content: center;
        button{
            margin-right: 10px;
        }
    }
    .UserAdd{
        width: 100%;
        height: 50px;
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
    }
</style>